<?php
include_once dirname(dirname(dirname(dirname(dirname(__FILE__)))))."/common.php";
\ns_core\m_load::load("ns_model.delivery.cdn_delivery_explain");
class delivery extends \ns_model\delivery\cdn_delivery_explain
{
    public function explain()
    {
        $fuc_name = (string)$this->get_c2_type();
        if(empty($fuc_name))
        {
            return $this->write_log_return('C2类型参数为空', NS_CDS_FAIL);
        }
        return $this->save_exec_log($this->$fuc_name());
    }

    /**
     * 注入CDN，主媒资不注入
     * @return array
     */
    public function video()
    {
        return $this->is_ok(NS_CDS_CDN_SUCCE, '成功');
    }
    /**
     * 注入CDN，分集不注入
     * @return array
     */
    public function index()
    {
        return $this->is_ok(NS_CDS_CDN_SUCCE, '成功');
    }

    /**
     * 片源注入CDN
     * @return array
     */
    public function media()
    {
        $action = $this->get_c2_info('action');
        if ($action === NS_CDS_DELETE)
        {
            return $this->media_destroy();
        }
        else
        {
            $action = "REGIST";
        }
        $arr_video_info = $this->get_video_info();
        if (empty($arr_video_info))
        {
            return $this->write_log_return("C2任务video数据错误，执行注入CDN失败", NS_CDS_FAIL);
        }
        /*******获取主媒资CDN注入ID******/
        $cdn_video_import_id = $this->get_video_cdn_import_id('video');
        if (empty($cdn_video_import_id))
        {
            return $this->write_log_return("主媒资C2任务生成主媒资CDN注入ID失败", NS_CDS_FAIL);
        }

        $arr_index_info = $this->get_index_info();
        if (empty($arr_index_info))
        {
            return $this->write_log_return("C2任务index数据错误，执行注入CDN失败", NS_CDS_FAIL);
        }

        $arr_media_info = $this->get_media_info();
        if (empty($arr_media_info))
        {
            return $this->write_log_return("C2任务media数据错误，执行注入CDN失败", NS_CDS_FAIL);
        }
        /*******获取CDN注入ID******/
        $cdn_import_id = $this->get_video_cdn_import_id();
        if (empty($cdn_import_id))
        {
            return $this->write_log_return("主媒资C2任务生成片源CDN注入ID失败", NS_CDS_FAIL);
        }

        //获取播控平台资源库栏目--用于获取栏目对于关系与资源类型
        $categorys = $this->get_category_info();
        if($categorys['ret'] != NS_CDS_SUCCE)
        {
            return $this->write_log_return($categorys['reason'],NS_CDS_FAIL);
        }
        $category_name = '';
        foreach ($categorys['data_info'] as $category)
        {
            if ((string)$category['id'] == (string)$arr_video_info['base_info']['nns_category_id'])
            {
                $category_name = $category['name'];
                break;
            }
        }
        //片源清晰度
        $is_hd = true;
        if(!empty($arr_media_info['base_info']['nns_mode']) && in_array(strtolower($arr_media_info['base_info']['nns_mode']),array('low','std')))
        {
            $is_hd = false;
        }
        //文件大小
        $file_size = '1';
        if((int)$this->get_c2_info('file_size') > 0)
        {
            $file_size = $this->get_c2_info('file_size');
        }
        elseif (strlen($this->get_c2_info('file_size')) <= 0 && (int)$arr_media_info['base_info']['nns_file_size'] > 0)
        {
            $file_size = $arr_media_info['base_info']['nns_file_size'];
        }
        //文件地址
        $file_path = $arr_media_info['base_info']['nns_url'];
        if(!empty($this->get_c2_info('file_path')))
        {
            $file_path = $this->get_c2_info('file_path');
        }
        //program数据构造【主媒资】
        $this->pid = strtoupper($arr_video_info['base_info']['nns_producer']);
        $this->offerid = $arr_media_info['base_info']['nns_ext_url'];
        $data = array(
            'Program' => array(
                'Provider' => $this->pid,//提供商ID，四位
                'ProgramID' => $cdn_video_import_id,//主媒资全局ID，20位
                'Title' => $arr_video_info['base_info']['nns_name'],//名称
                'EpisodeCount' => $arr_video_info['base_info']['nns_all_index'],//总集数
                'Title_Sort_Name' => !empty($category_name) ? $category_name : '电影',//类型
                'Director' => str_replace("/",",",$arr_video_info['base_info']['nns_director']),//导演,多个以逗号分隔
                'Actors_Display' => str_replace("/",",",$arr_video_info['base_info']['nns_actor']),//演员,多个以逗号分隔
                'Writer_Display' => '',//编剧,多个以逗号分隔
                'Producer' => '',//制片人,多个以逗号分隔
                'Studio' => '',//制片厂
                'Year' => $arr_video_info['ex_info']['year'],//发行年代
                'Country_of_Origin' => $arr_video_info['base_info']['nns_area'],//发行国家
                'Rating' => '', //观看级别。TV-Y/TV-Y7/TV-G/TV-PG/TV-14/TV-MA
                'Genre' => $arr_video_info['base_info']['nns_kind'],//节目类型。动作片/喜剧片/爱情片/恐怖片/科幻片/动画片/故事片
                'Summary_Short' => $arr_video_info['base_info']['nns_summary'],//简介
            ),
            //节目计费信息，由AAA单独管理，此处不进行注入
//            'Terms' => array(
//                'startDateTime' => '2013-04-26T20:11:00',//用于表示节目的上线时间，固定格式为yyyy-MM-ddTHH:mm:ss
//                'EndDateTime' => '',//用于表示节目的下线时间，固定格式为yyyy-MM-ddTHH:mm:ss
//                'RentalPeriod' => '',//该数据必须为一整数值，表示租用期，单位是秒。即用户购买一次，在该指定时间内再次点播都是免费的，一般设置成24小时。默认值为86400（即为24小时）
//                'SuggestedPrice' => '',//该数据表示节目定价，精确到小数点后两位的浮点型值，单位是元默认值为0
//            ),
            'Movie' => array(
                'ID' => $this->offerid,//offerid
                'Episode_ID' => $arr_index_info['base_info']['nns_index'] + 1,//集次序号，用于决定集次排序，如果是单集的电影可填1
                'Episode_Name' => $arr_index_info['base_info']['nns_name'],//集次的名称
                'Summary_Medium' => $arr_index_info['base_info']['nns_summary'],//集次的简介
                'Run_Time' => gmstrftime('%H:%M:%S',$arr_media_info['base_info']['nns_file_time_len']),//播放时长，格式为 HH:mm:ss
                'Audio_Type' => '',//音频类型。Stereo/Mono/Dolby ProLogic/Dolby Digital/Dolby 5.1
                'Screen_Format' => '',//屏幕模式。Standard/Widescreen/Letterbox/OAR
                'HDContent' => $is_hd ? 'Y' : 'N',//是否高清。Y/N
                'Languages' => '',//配音语言
                'Subtitle_Languages' => '',//字幕语言
                'Dubbed_Languages' => '',//译制语言
                'Content_FileSize' => $file_size,//文件大小(单位: 字节)(整数值)
                'Content' => $file_path,//节目视频文件名，必须与视频文件名匹配
            ),
            //海报信息，由于分辨率，文件大小为poster节点必填项，故不注入海报
//            'Poster' => array(
//                'Image_Aspect_Ratio' => '',//图片分辨率，图片分辨率不要太大。
//                'Content_FileSize' => '',//文件大小(单位: 字节)(整数值)
//                'Content' => '',//节目海报文件名，必须与图片文件名匹配
//            ),
        );
        $xml = $this->_make_array_xml($data);
        $params = array(
            'nns_task_type' => "Movie",//媒资类型
            'nns_action' => $action, //行为动作
            'nns_content' => $xml,//注入XML内容
            'nns_task_id' => $this->get_c2_info('id'),
            'nns_task_name' => $this->get_c2_info('name'),
        );
        return $this->execute($params);
    }

    /**
     * 片源删除，删除CDN为同步返回删除状态
     */
    public function media_destroy()
    {
        $arr_video_info = $this->get_video_info();
        if (empty($arr_video_info))
        {
            return $this->write_log_return("C2任务video数据错误，执行注入CDN失败", NS_CDS_FAIL);
        }
        /*******获取主媒资CDN注入ID******/
        $cdn_video_import_id = $this->get_video_cdn_import_id('video');
        if (empty($cdn_video_import_id))
        {
            return $this->write_log_return("主媒资C2任务生成主媒资CDN注入ID失败", NS_CDS_FAIL);
        }
        $arr_index_info = $this->get_index_info();
        if (empty($arr_index_info))
        {
            return $this->write_log_return("C2任务index数据错误，执行注入CDN失败", NS_CDS_FAIL);
        }
        $arr_media_info = $this->get_media_info();
        if (empty($arr_media_info))
        {
            return $this->write_log_return("C2任务media数据错误，执行注入CDN失败", NS_CDS_FAIL);
        }
        //program数据构造【主媒资】
        $this->pid = strtoupper($arr_video_info['base_info']['nns_producer']);
        $this->offerid = $arr_media_info['base_info']['nns_ext_url'];

        $cdn_code = NS_CDS_CDN_SUCCE;
        $params = array(
            'nns_task_type' => "Movie",//媒资类型
            'nns_action' => 'DELETE', //行为动作
            'nns_task_id' => $this->get_c2_info('id'),
            'nns_task_name' => $this->get_c2_info('name'),
        );
        //生成CDN工单唯一ID
        $params['nns_id'] = $this->get_guid();
        $params['nns_result'] = NS_CDS_CDN_SUCCE;
        $params['nns_send_time'] = date("Y-m-d H:i:s");
        //offeruriid为空 或者 C2任务处于失败状态，则直接改为成功
        if(empty($arr_media_info['base_info']['nns_content_id']) || $this->get_c2_info('nns_status') == NS_CDS_CDN_FAIL)
        {
            $xml = "";
            $local_url = '';
            $params['nns_notify_result'] = NS_CDS_CDN_NOTIFY_SUCCE;
            $params['nns_notify_time'] = date('Y-m-d H:i:s');
            $reason = "offeruriid【media的nns_content_id】为空或者C2任务处于失败状态";
            $this->write_log_return($reason);
        }
        else
        {
            $data = array(
                'Program' => array(
                    'Provider' => $this->pid,//提供商ID，四位
                    'ProgramID' => $cdn_video_import_id,//主媒资全局ID，20位
                    'Title' => $arr_video_info['base_info']['nns_name'],//名称
                ),
                'Movie' => array(
                    'ID' => $this->offerid,//offerid
                    'offerUriId' => $arr_media_info['base_info']['nns_content_id'],
                    'Episode_ID' => $arr_index_info['base_info']['nns_index'] + 1,
                ),
            );
            $xml = $this->_make_array_xml($data);
            $task = $this->save_execute_import_content_v2($xml);
            if($task['ret'] != 0)
            {
                return $this->write_log_return($task['reason'], NS_CDS_FAIL);
            }
            $local_url = $task['data_info']['base_dir'];

            $this->write_log_return("CDN执行删除：".var_export(array('offerUriId' => $arr_media_info['base_info']['nns_content_id']),true));

            try
            {
                global $g_bk_web_url;
                $project = evn::get('project');
                $wsdl_addr = trim(trim($g_bk_web_url, '/'), '\\') . "/v2/ns_api/" . $project ."/delivery/" . $this->str_sp_id . "/inspur_service.php?wsdl";
                $soap_client = new SOAPClient($wsdl_addr, array('trace'=>true));
                //添加soapheader
                $soap_header = new SoapHeader('inspurCMS','HeadUserCheck',(object)array('Username'=>'ContentManage','Password'=>'ContentManage'));
                $soap_client->__setSoapHeaders($soap_header);

                $client_re = $soap_client->DeleteOffer(array('offerUriId' => $arr_media_info['base_info']['nns_content_id']));
                $this->write_log_return("CDN同步返回：".var_export($client_re,true));
                $client_code = $client_re->DeleteOfferResult;

                if($client_code == 0)
                {
                    $params['nns_notify_result'] = NS_CDS_CDN_NOTIFY_SUCCE;
                    $reason = "删除成功";
                }
                else
                {
                    $cdn_code = NS_CDS_CDN_FAIL;
                    $params['nns_notify_result'] = NS_CDS_CDN_NOTIFY_FAIL;
                    $inspur_code = array(
                        '-1' => '已无此offer的记录',
                        '111' => '验证失败',
                        '301' => '输入的OfferUriId的格式不正确',
                    );
                    $reason = isset($inspur_code[$client_code]) ? $client_code.$inspur_code[$client_code] : $client_code.'删除失败';
                }
                $params['nns_notify_fail_reason'] = $reason;
                $params['nns_notify_time'] = date('Y-m-d H:i:s');
                $this->write_log_return($reason);
            }
            catch (Exception $e)
            {
                $cdn_code = NS_CDS_CDN_FAIL;
                $params['nns_result'] = NS_CDS_CDN_FAIL;
                $params['nns_result_fail_reason'] = '抛出异常,发送CDN失败,请联系工作人员';
                $this->write_log_return($params['nns_result_fail_reason']);
            }

        }

        $params['nns_content'] = $xml;
        $params['nns_url'] = $local_url;

        //生成C2日志
        $build_c2 = $this->build_c2_log($params);
        if($build_c2['ret'] != NS_CDS_SUCCE)
        {
            return $this->write_log_return($build_c2['reason'], $build_c2['ret']);
        }

        return $this->is_ok($cdn_code, $reason);
    }
    /**
     * 生成xml
     * @param unknown $data 数组对象
     */
    private function _make_array_xml($data)
    {
        $obj_dom = new DOMDocument("1.0", 'utf-8');
        $attr = $obj_dom->createElement("DATA");
        $attr_data = $obj_dom->appendChild($attr);
        foreach ($data as $attr_key => $value)
        {
            $domAttribute = $obj_dom->createElement($attr_key);
            $attr_key = $attr_data->appendChild($domAttribute);
            foreach ($value as $key=>$val)
            {
                $child_attr = $obj_dom->createElement($key);
                $child_key = $attr_key->appendChild($child_attr);
                $content = $obj_dom->createTextNode($val);
                $child_key->appendchild($content);
            }

        }
        return $obj_dom->saveXML();
    }
    /**
     * CDN注入统一发送器入口
     * 按项目进行自定义发送处理
     * @param $params array(
     *       'nns_task_type' =>类型,
     *       'nns_action' => 行为动作，
     *       'nns_content' => 注入XML内容
     * );
     * @return array('ret','reason');
     */
    public function execute($params)
    {
        $cdn_code = NS_CDS_CDN_LOADING;
        //生成CDN工单唯一ID
        $params['nns_id'] = $this->get_guid();
        $str_pid_len = strlen($this->pid);
        $ftp_path = $this->pid.substr($this->offerid, $str_pid_len, 6).'/'.$this->offerid;
        $task = $this->save_execute_import_content_v2($params['nns_content'], $this->arr_sp_config['xml_ftp'], false, $ftp_path, 'data.xml');
        if($task['ret'] != 0)
        {
            $this->write_log_return($task['reason'], NS_CDS_FAIL);
            return $task;
        }
        $local_url = $task['data_info']['base_dir'];
        $this->write_log_return("CDN执行新增：".var_export(array('strDir' => $ftp_path),true));

        try
        {
            global $g_bk_web_url;
            $project = evn::get('project');
            $wsdl_addr = trim(trim($g_bk_web_url, '/'), '\\') . "/v2/ns_api/" . $project ."/delivery/" . $this->str_sp_id . "/inspur_service.php?wsdl";
            $soap_client = new SOAPClient($wsdl_addr, array('trace'=>true));
            //添加soapheader
            $soap_header = new SoapHeader('inspurCMS','HeadUserCheck',(object)array('Username'=>'ContentManage','Password'=>'ContentManage'));
            $soap_client->__setSoapHeaders($soap_header);

            $client_re = $soap_client->InjectOffer(array('strDir' => $ftp_path));
            $this->write_log_return("CDN同步返回：".var_export($client_re,true));
            $client_code = $client_re->InjectOfferResult;
            if($client_code == 0)
            {
                $import_code = NS_CDS_CDN_NOTIFY_SUCCE;
                $reason = "发送成功";
            }
            else
            {
                $import_code = NS_CDS_CDN_FAIL;
                $cdn_code = NS_CDS_CDN_FAIL;
                $inspur_code = array(
                    '1' => '互动系统中添加过该offer，状态：正在排队或注入',
                    '2' => '互动系统中添加过该offer，状态：已经注入',
                    '-1' => '互动系统中添加过该 offer，状态：注入失败',
                    '100' => '参数strDir为空',
                    '111' => '验证错误',
                    '101' => '互动系统中已有该节目和集次的节目记录，勿重复注入',
                    '102' => 'data.xml文件中描述的文件与FTP上的文件不一致',
                    '201' => '服务器端数据库网络不通',
                    '301' => '服务器端FTP不通',
                    '600' => '存储空间已满，无法注入更多的内容。请先删除一些内容',
                );
                $reason = isset($inspur_code[$client_code]) ? $client_code.$inspur_code[$client_code] : $client_code.'媒资描述文件data.xml有误';
            }
            $this->write_log_return($reason, $cdn_code);
        }
        catch (Exception $e)
        {
            $import_code = NS_CDS_CDN_FAIL;
            $cdn_code = NS_CDS_CDN_FAIL;
            $reason = '抛出异常,发送CDN失败,请联系工作人员';
            $this->write_log_return($reason, $cdn_code);
        }
        $params['nns_url'] = $local_url;
        $params['nns_result'] = $import_code;
        $params['nns_send_time'] = date("Y-m-d H:i:s");
        $params['nns_result_fail_reason'] = $reason;
        //生成C2日志
        $build_c2 = $this->build_c2_log($params);
        if($build_c2['ret'] != NS_CDS_SUCCE)
        {
            return $this->write_log_return($build_c2['reason'], $build_c2['ret']);
        }

        return $this->is_ok($cdn_code, $reason);
    }
    /**
     * 调用进行反馈
     * @param $OfferId 片源ext_url
     * @param $OfferUriId 需要保存的contentid
     * @param $code 状态码，0成功，其他失败
     * @return $reason 反馈的原因
     */
    public function notify($OfferId, $OfferUriId, $code, $reason)
    {
        if(empty($OfferId))
        {
            return $this->write_log_return('OfferId为空，不接收当前的CDN反馈消息', NS_CDS_FAIL);
        }
        if(empty($reason))
        {
            $reason = '注入CDN成功';
            $notify_result = 'CDN反馈成功';
        }
        else
        {
            $notify_result = $reason;
        }
        //通过offerid获取片源ID
        $vod_media_re = \nl_vod_media_v2::query_by_condition(\m_config::get_dc(), array('nns_ext_url' => $OfferId));
        if($vod_media_re['ret'] != NS_CDS_SUCCE || !is_array($vod_media_re['data_info']))
        {
            return $this->write_log_return('CDS根据OfferId查询文件失败：'.$OfferId, NS_CDS_FAIL);
        }
        $vod_media_id = $vod_media_re['data_info'][0]['nns_id'];

        $this->str_source_id = $vod_media_re['data_info'][0]['nns_cp_id'];

        //CDN反馈状态
        if($code != NS_CDS_SUCCE)
        {
            $cdn_code = NS_CDS_CDN_NOTIFY_FAIL;
            $notify_result = $reason;
        }
        else
        {
            if(empty($OfferUriId))
            {
                return $this->write_log_return('CDN反馈成功，但OfferUriId为空，不接收当前的CDN反馈消息', NS_CDS_FAIL);
            }
            $cdn_code = NS_CDS_CDN_NOTIFY_SUCCE;
            //修改片源ext_url为offeruriid
            $update_re = \nl_vod_media_v2::edit_v2(\m_config::get_dc(), array('nns_content_id' => $OfferUriId), $vod_media_id);
            if($update_re['ret'] != NS_CDS_SUCCE)
            {
                return $this->write_log_return('CDN反馈成功，CDS修改OfferUriId发生错误。'.$update_re['reason'], NS_CDS_FAIL);
            }
            //片源注入成功且开启删除物理文件开关，则删除FTP上物理文件
            $arr_source_config = \m_config::_get_cp_info($this->str_source_id);
            $this->arr_source_config = isset($arr_source_config['data_info']['nns_config']) ? $arr_source_config['data_info']['nns_config'] : array();
            if((int)$this->arr_source_config['del_cp_file_enabled'] === 1)
            {
                $cp_file_url = $vod_media_re['data_info'][0]['nns_url'];
                if(strpos($vod_media_re['data_info'][0]['nns_url'],"ftp://") === false)
                {
                    $cp_file_url = rtrim($this->arr_source_config['down_url_real'],"/") . "/" . ltrim($vod_media_re['data_info'][0]['nns_url'],"/");
                }
                $ftp_passive = (int)$this->arr_source_config['down_method_ftp'] ? false : true;
                $this->write_log_return("删除物理文件：".$cp_file_url."，模式：".var_export($ftp_passive,true));
                //只支持FTP的删除
                if(strpos($cp_file_url,"ftp://") !== false)
                {
                    $arr_url = parse_url($cp_file_url);
                    $ftp = new nns_ftp($arr_url['host'], $arr_url['user'], $arr_url['pass'], $arr_url['port']);
                    $ftpcon = $ftp->connect(10, $ftp_passive);
                    if ($ftpcon)
                    {
                        $del_file_re = $ftp->delete($arr_url['path']);
                        $this->write_log_return("删除物理文件状态：".var_export($del_file_re,true));
                    }
                    else
                    {
                        $this->write_log_return("删除物理文件FTP链接失败");
                    }
                }
                else
                {
                    $this->write_log_return("不能删除非FTP服务上的文件");
                }
            }
        }

        $c2_params = array(
            'nns_status' => NS_CDS_CDN_LOADING,
            'nns_ref_id' => $vod_media_id,
            'nns_type' => NS_CDS_MEDIA,
            'nns_action' => NS_CDS_ADD,
            'nns_org_id' => $this->str_sp_id,
        );
        return $this->is_notify_ok_v2($c2_params, $cdn_code, $reason, $notify_result);
    }
}
